<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>1.canvas应用实例之神奇的小球</title>
</head>
<style>
    * {
        padding: 0;
        margin: 0;
    }
    canvas {
        display: block;
        border: 1px solid black;
    }
</style>
<body>
    <!-- 兼容性处理，当浏览器不支持canvas时，将以普通标签来解析canvas标签 -->
    <canvas id="canvas" width="500px" height="500px">对不起，您的浏览器版本过低，升级浏览器再访问。</canvas>
    <script>
        // 1.获取画布对象
        let canvas = document.querySelector('#canvas');
        // 2. 获取绘画环境
        let ctx = canvas.getContext('2d');
        //取随机数
        var randomNum = function (num) {
                return Math.random()*num
        };
        let config = {
            w: 500,
            h: 500,
        };
        console.log('config', config);
        let w=h=500;
        let x = 500;
        //小球的构造函数
        function Ball(x, y, r, color) { 
            this.x = randomNum(5) + 60;
            this.y = randomNum(5) + 60;
            this.r = randomNum(50) + 10;
            this.color = '#' + parseInt(Math.random()*0xffffff).toString(16);
            this.xSpeed = randomNum(3) + 2;
            this.ySpeed = randomNum(3) + 1;
         }
        Ball.prototype = {
            //创建小球
            createBall() {
                //更新坐标
                this.run();

                ctx.beginPath();
                //ctx.arc(x轴坐标，y轴坐标，r半径，起始角度，结束角度，是否逆时针画)
                ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false);
                ctx.fillStyle= this.color;
                ctx.fill();
                ctx.stroke();
            },
            //小球运动（进行碰撞检测）
            run() {
                //x轴方向进行碰撞检测
                if(this.x - this.r<= 0  || this.x + this.r >= config.w) {
                    this.xSpeed = - this.xSpeed;
                };
                //y轴方向进行碰撞检测
                if(this.y - this.r<= 0  || this.y + this.r >= config.w) {
                    this.ySpeed = - this.ySpeed;
                };
                this.x += this.xSpeed;
                this.y += this.ySpeed;
            }

        };

        //实例化小球
        let ballArr = [];
        // ball1.createBall();
        //循环生成多个小球
        for(var i=0; i<100;i++) {
            let ball = new Ball();
            ballArr.push(ball);
            ball.createBall();
        }
        console.log('ballArr=>', ballArr)
        let timer = setInterval(_=>{
            ctx.clearRect(0, 0, config.w, config.h);
            ballArr.forEach(item=>{
                item.createBall();
            });
        }, 10);






        
        // 监听ctx的用户行为
        let startPosition ={};
        let endPosition ={};
        canvas.addEventListener('mousemove', (e)=>{
            if (window.newball) {
                newball.x = e.clientX;
                newball.y = e.clientY;
                ctx.clearRect(0,0,config.w,config.h);
                newball.createBall();
                console.log(99);
            }
        })
        canvas.addEventListener('mousedown', (e)=>{
            console.log('mouseDown',e);
            startPosition ={
                x: e.clientX,
                y: e.clientY,
            };
        })
        canvas.addEventListener('mouseup', (e)=>{
            console.log('mouseup',e);
            endPosition ={
                x: e.clientX,
                y: e.clientY,
            };
            clearInterval(timer);
            ctx.clearRect(0, 0, config.w, config.h);
            ballArr.forEach(item => {
                item = null;
            })
            // 计算小球的中心点
            let centerXY = {
                x: startPosition.x,
                y: startPosition.y
            };
            // 计算小球的半径
            let newr = Math.sqrt(Math.pow((startPosition.x - endPosition.x), 2) + Math.pow((startPosition.y - endPosition.y), 2));
            console.log('result',centerXY,newr);

            newball = new Ball();
            newball.x = centerXY.x;
            newball.y = centerXY.y;
            newball.r = newr;
            newball.createBall();
            
        })

        window.addEventListener('keydown', (e)=>{
            if (window.newball) {
                ctx.clearRect(0,0,config.w,config.h);
                window.newball = null;
            }
            console.log(888)
        })

    </script>
</body>
</html>